<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use fast\Random;
use think\addons\Controller;
use Exception;
use think\Db;
use Yansongda\Pay\Pay;
use app\common\model\OrderPay;
use app\admin\model\Play as PlayModel;
use app\common\model\Order;
use app\common\model\OrderLog;
use app\api\service\UserService;
use app\common\model\User;

/**
 * 微信支付宝整合插件首页
 *
 * 此控制器仅用于开发展示说明和测试，请自行添加一个新的控制器进行处理返回和回调事件，同时删除此控制器文件
 *
 * Class Index
 * @package addons\epay\controller
 */
class Index extends Controller
{

    protected $layout = 'default';

    protected $config = [];

    public function _initialize()
    {
        parent::_initialize();
        if (!config("app_debug")) {
            $this->error("仅在开发环境下查看");
        }
    }

    public function index()
    {
        $this->view->assign("title", "微信支付宝整合");
        return $this->view->fetch();
    }

    /**
     * 体验，仅供开发测试
     */
    public function experience()
    {
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);

        //订单标题
        $title = '测试订单';

        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);

        return $response;
    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
  //       $param = [
  //   'gmt_create' => '2023-04-26 11:04:05',
  // 'charset' => 'utf-8',
  // 'seller_email' => '1528782433@qq.com',
  // 'subject' => '商家支付账单',
  // 'sign' => 'ili6MJVhrK0klB3POhQQTL5/3FstOt11Xhyz9FiZXClQk8xmvZ/au0g+FPv8AFlzozgK7Zo6qDIo2D0JAuHYfLlCfo7UmBugIRzxeB3ofzZUSMWSkipHZH39uQub04M9g158E9iOGmpDEYbngw2DCG6e1gyiW7MhpHSP/bh6mnSUd+GgHatC382WMk5F5CiDsM8nghRxjmhjuu9KvIhrGlsW4hlBn+5h1Uz0u3dGqMeNDq56MmP+TufRhxFMfZYdRey1xgnweHnvKsBDdA0rwvNpl3daHggRc3exeOEDkjqV2V9p2HyVYNzZ1Gk5UnYCutRCv7FH8GdDtnmIOmRZzQ==',
  // 'buyer_id' => '2088802708398713',
  // 'invoice_amount' => '0.10',
  // 'notify_id' => '2023042601222110406098711434648151',
  // 'fund_bill_list' => '[{"amount":"0.10","fundChannel":"PCREDIT"}]',
  // 'notify_type' => 'trade_status_sync',
  // 'trade_status' => 'TRADE_SUCCESS',
  // 'receipt_amount' => '0.10',
  // 'buyer_pay_amount' => '0.10',
  // 'app_id' => '2021003186663016',
  // 'sign_type' => 'RSA2',
  // 'seller_id' => '2088641013979026',
  // 'gmt_payment' => '2023-04-26 11:04:05',
  // 'notify_time' => '2023-04-26 11:04:06',
  // 'version' => '1.0',
  // 'out_trade_no' => '813540276861',
  // 'total_amount' => '0.10',
  // 'trade_no' => '2023042622001498711402221138',
  // 'auth_app_id' => '2021003186663016',
  // 'buyer_logon_id' => '153****1520',
  // 'point_amount' => '0.00',
  // 'addon' => 'epay',
  // 'controller' => 'api',
  // 'action' => 'notifyx',
  // 'type' => 'alipay',
  //       ];
  //       var_dump('http://chbc.taozhenhao.com/addons/epay/api/notifyx/type/alipay?'.http_build_query($param));exit;
        $type = $this->request->param('type');
        $pay = \addons\epay\library\Service::checkNotify($type);
        \think\Log::write('验签结果:'.json_encode($pay));
        // if (!$pay) {
        //     echo '签名错误';
        //     \think\Log::write('签名错误');
        //     return;
        // }
        // $data = $pay->verify();

        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $param = $this->request->param();
        // if ($type=='wechat') {
        //     $param = $data;
        // }
        $OrderPay = OrderPay::where('pay_no',$param['out_trade_no'])->find();
        if ($OrderPay['pay_status']==1) {
            \think\Log::write('orderpay:已支付');
            echo '已支付';
            return;
        }
        if (!$OrderPay || !$OrderPay['play_nos']) {
            \think\Log::write('paydata:无支付单号');
            echo '参数有误';
            return;
        }
        // $play_nos = explode(',', $OrderPay['play_nos']);
        // if (!$play_nos) {
        //     \think\Log::write('paydata:play_nos参数错误');
        //     echo '参数有误';
        //     return;
        // }
        // $PlayModel = new PlayModel();
        // $where= [];
        // $where['play_no'] = ['in',$play_nos];
        // $play = $PlayModel->where($where)->select();
        // if (!$play) {
        //     \think\Log::write('paydata:play不存在');
        //     echo '参数有误';
        //     return;
        // }
        $User = new \app\common\model\User();
        $userinfo = $User->get($OrderPay['user_id']);
        $order_nos = [];
        $play_nos = [];
        Db::startTrans();
        try {
            // foreach ($play as $k1 => $v1) {
            $order = Db::name('order_pay_item')->alias('opi')->join('play_order po','po.play_order_no=opi.play_order_no')->field('po.*')->where(['opi.pay_no'=>$OrderPay['pay_no']])->select();
            // 每个店铺的支付总金额
            $sum = [];
            if ($order) {
                foreach ($order as $key => $value) {
                    if (!in_array($value['play_no'], $play_nos)) {
                        $play_nos[] = $value['play_no'];
                    }
                    // orderlog
                    OrderLog::create([
                        'play_order_id' => $value['id'],
                        'play_order_no' => $value['play_order_no'],
                        'create_by' => $userinfo['nickname'],
                        'create_by_id' => $userinfo['id'],
                        'is_front' => 1,
                        'info' => '商家支付h5账单',
                    ]);
                    Order::where(['id'=>$value['id']])->update(['is_pay'=>1,'pay_time'=>time()]);
                    $order_nos[] = $value['play_order_no'];
                    // 中间人佣金
                    $shop = Db::name('shop')->where(['shop_no'=>$value['shop_no']])->field('middleman_id,shop_no')->find();
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                    if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                        $User->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $value['play_order_no']);
                    }
                    $amt = round($value['service_charge_amt']+$value['actual_rebate_amt'],2);
                    if (!isset($sum[$shop['shop_no']])) {
                        $sum[$shop['shop_no']] = $amt;
                    } else {
                        $sum[$shop['shop_no']] = $sum[$shop['shop_no']]+$amt;
                    }
                }
            }
            foreach ($play_nos as $key => $play_no) {
                $play = PlayModel::where('play_no', $play_no)->find();
                if (Order::where(['play_no'=>$play_no,'is_pay'=>1])->count()==$play['num']-$play['stock'] && $play['num']-$play['stock']>0) {
                    $play->play_status = 5;
                    $play->pay_status = 2;
                } elseif (Order::where(['play_no'=>$play_no,'order_status'=>['in',[3,-9]]])->count()==$play['num']-$play['stock'] && $play['num']-$play['stock']>0) {
                    $play->play_status = 3;
                    $play->pay_status = 1;
                } else {
                    $play->play_status = 4;
                    $play->pay_status = 1;
                }
                $play->last_pay_time = time();
                $play->update_by = $OrderPay['user_id'];
                $play->save();
            }
            // }
            //判定是否存在用户分销
            // $UserService = new UserService();
            // $res = $UserService->userDistribution($order_nos);
            // if (!$res) {
            //     Db::rollback();
            //     echo '用户返利计算错误';
            //     return;
            // }
            //判定是否存在商家分销
            //
            $OrderPay->pay_status = 1;
            $tran_no = '';
            if ($type=='alipay') {
                $tran_no = $param['trade_no'];
            } elseif ($type=='wechat') {
                $tran_no = $param['transaction_id'];
            }
            $OrderPay->tran_no = $tran_no;
            $OrderPay->save();

            // 更新商家账单
            $bill_list = Db::name('bill_list')->order('id DESC')->find();
            if ($sum) {
                foreach ($sum as $key => $value) {
                    $where = 'create_dt="'.$bill_list['create_dt'].'" and shop_no='.$key;
                    $bill_list = Db::name('bill_list')->where($where)->field('*')->find();
                    if ($bill_list) {
                        $update = [];
                        $play_status = '正常';
                        $last_pay_time = time();// 到账时间
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and last_pay_time=0')->where('update_dt<"'.date('Y-m-d H:i:s',time()-259200).'"')->count();
                        if ($play) {
                            $play_status = '紧急账单';
                        }
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and last_pay_time=0')->where('update_dt<"'.date('Y-m-d H:i:s',time()-777600).'"')->count();
                        if ($play) {
                            $play_status = '异常账单';
                        }
                        $amount = $bill_list['total_money']-$value;
                        $update['last_pay_time'] = 0;
                        $update['total_money'] = 0;
                        $update['pay_status'] = '';
                        if ($amount>0) {
                            $update['pay_status'] = '待支付';
                            $update['total_money'] = round($amount,2);
                        } else {
                            $update['pay_status'] = '已支付';
                            $update['last_pay_time'] = $last_pay_time;
                        }
                        $update['play_status'] = $play_status;
                        $update['update_dt'] = date('Y-m-d H:i:s',time());
                        Db::name('bill_list')->where('id='.$bill_list['id'])->update($update);
                    }
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            \think\Log::write('paydata:'.print_r($e->getMessage()));
            echo '处理有误';
            return;
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }

}
